package com.z.common.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import jxl.Workbook;
import jxl.format.Border;
import jxl.write.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExportExcelUtil {
	/**
	 * 导出Excel
	 * @param response 
	 * @param fileName 文件名
	 * @param wrap 正文是否自动换行
	 * @param maxWidth 最大列宽
	 * @param verticalFreeze 冻结行
	 * @param horizontalFreeze 冻结列
	 * @param Title 表头
	 * @param listContent 正文list
	 * @return HttpServletResponse
	 */
	public static HttpServletResponse exportExcel(HttpServletResponse response, String fileName,
			boolean wrap,int maxWidth, int verticalFreeze, int horizontalFreeze,
			String[] Title, List<String[]> listContent) {
		try {
			OutputStream os = response.getOutputStream();// 取得输出流
			response.reset();// 清空输出流
			response.setHeader("Content-disposition", "attachment; filename="+ new String(fileName.getBytes(),"ISO8859-1"));  
			// 设定输出文件头
			response.setContentType("application/msexcel");// 定义输出类型
			//定义输出流，以便打开保存对话框_______________________end
			/** **********创建工作簿************ */
			WritableWorkbook workbook = Workbook.createWorkbook(os);
			/** **********创建工作表************ */
			WritableSheet sheet = workbook.createSheet("Sheet1", 0);
			/** **********设置纵横打印（默认为纵打）、打印纸***************** */
			jxl.SheetSettings sheetset = sheet.getSettings();
			sheetset.setProtected(false);
			sheetset.setVerticalFreeze(verticalFreeze);
			sheetset.setHorizontalFreeze(horizontalFreeze);
			/** ************设置单元格字体************** */
			WritableFont NormalFont = new WritableFont(WritableFont.ARIAL, 10);
			WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 10,WritableFont.BOLD);
			/** ************以下设置三种单元格样式，灵活备用************ */
			// 用于标题居中
			WritableCellFormat wcf_center = new WritableCellFormat(BoldFont);
			wcf_center.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
			wcf_center.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐
			wcf_center.setAlignment(Alignment.CENTRE); // 文字水平对齐
			wcf_center.setBackground(Colour.GRAY_25);
			wcf_center.setWrap(true); // 文字是否换行
			// 用于正文居左
			WritableCellFormat wcf_left = new WritableCellFormat(NormalFont);
			wcf_left.setBorder(Border.NONE, BorderLineStyle.THIN); // 线条
			wcf_left.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐
			wcf_left.setAlignment(Alignment.LEFT); // 文字水平对齐
			wcf_left.setWrap(wrap); // 文字是否换行
			
			/** ***************以下是EXCEL开头大标题，暂时省略********************* */
			//sheet.mergeCells(0, 0, colWidth, 0);
			//sheet.addCell(new Label(0, 0, "XX报表", wcf_center));
			/** ***************以下是EXCEL第一行列标题********************* */
			for (int i = 0; i < Title.length; i++) {
				sheet.addCell(new Label(i, 0,Title[i],wcf_center));
			}
			/** ***************以下是EXCEL正文数据********************* */
			int i=1;
			Map<Integer,Integer> column_min_width = new HashMap<>();
			for(String[] obj:listContent){
				int j=0;
				for(String str:obj){
					int width = Title[j].length();
					if(StringUtils.isNotEmpty(str)){
						String[] strs = str.split("\r\n");
						for(String s : strs){
							if(s.length()>width){
								width = s.length()>maxWidth?maxWidth:s.length();
							}
						}
					}
					if(null == column_min_width.get(j) || width > column_min_width.get(j)){
						column_min_width.put(j, width);
					}
					sheet.setColumnView(j, column_min_width.get(j)+5);//设置自动行高(i为行号)
					sheet.addCell(new Label(j, i,str,wcf_left));
					j++;
				}
				i++;
			}
			/** **********将以上缓存中的内容写到EXCEL文件中******** */
			workbook.write();
			/** *********关闭文件************* */
			workbook.close();
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		} catch (WriteException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
        return response;
	}

	/**
	 * 下载文件
	 * @param response
	 * @param path
	 * @return
	 */
	public static HttpServletResponse downloadFile(HttpServletResponse response, String path){
		try {
			// path是指欲下载的文件的路径。
	        File file = new File(path);
	        // 取得文件名。
	        String filename = file.getName();
	        // 取得文件的后缀名。
	        //String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
	        // 以流的形式下载文件。
	        BufferedInputStream fis = new BufferedInputStream(new FileInputStream(path));
	        byte[] buffer = new byte[fis.available()];
	        fis.read(buffer);
	        fis.close();
	        // 清空response
	        response.reset();
	        // 设置response的Header
	        response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(), "ISO-8859-1"));
	        response.addHeader("Content-Length", "" + file.length());
	        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
	        response.setContentType("application/octet-stream");
	        toClient.write(buffer);
	        toClient.flush();
	        toClient.close();
	        file.deleteOnExit();
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
        return response;
	}
}
